var ROUND_SUPPORTED_PRECISION_MAX = 20
// 脚本用途：计算Y轴，min值 和 max值
// 此脚本导出方法 calcNiceExtent
// 参数1：splitNumber => 5
// 参数2：[0, 15223.23] 含有最大最小值的数组
// 返回值：[0, 20000] 比较符合用户易读性的值
export function calcNiceExtent(splitNumber, extent) {
  splitNumber = splitNumber || 5
  if (extent[0] === extent[1]) {
    if (extent[0] !== 0) {
      var expandSize = extent[0]
      extent[1] += expandSize / 2
      extent[0] -= expandSize / 2
    } else {
      extent[1] = 1
    }
  }
  var span = extent[1] - extent[0]
  if (!isFinite(span)) {
    extent[0] = 0
    extent[1] = 1
  }
  var interval = calcNiceTicks(extent, splitNumber) // let extent = this._extent;
  extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval)
  extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval)
  return extent
}
/**
 * @param extent Both extent[0] and extent[1] should be valid number.
 *               Should be extent[0] < extent[1].
 * @param splitNumber splitNumber should be >= 1.
 */
function intervalScaleNiceTicks(extent, splitNumber) {
  var span = extent[1] - extent[0]
  var interval = nice(span / splitNumber, true)
  return interval
}
function calcNiceTicks(extent, splitNumber) {
  splitNumber = splitNumber || 5
  var span = extent[1] - extent[0]
  if (!isFinite(span)) {
    return
  }
  if (span < 0) {
    span = -span
    extent.reverse()
  }
  var interval = intervalScaleNiceTicks(extent, splitNumber)
  return interval
}
function roundNumber(x, precision, returnStr) {
  if (precision == null) {
    precision = 10
  } // Avoid range error
  precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX) // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  x = (+x).toFixed(precision)
  return returnStr ? x : +x
}
/**
 * Exponent of the quantity of a number
 * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
 *
 * @param val non-negative value
 * @return
 */
function quantityExponent(val) {
  if (val === 0) {
    return 0
  }
  var exp = Math.floor(Math.log(val) / Math.LN10)
  if (val / Math.pow(10, exp) >= 10) {
    exp++
  }
  return exp
}
function nice(val, round) {
  var exponent = quantityExponent(val)
  var exp10 = Math.pow(10, exponent)
  var f = val / exp10 // 1 <= f < 10
  var nf
  if (round) {
    if (f < 1.5) {
      nf = 1
    } else if (f < 2.5) {
      nf = 2
    } else if (f < 4) {
      nf = 3
    } else if (f < 7) {
      nf = 5
    } else {
      nf = 10
    }
  } else {
    if (f < 1) {
      nf = 1
    } else if (f < 2) {
      nf = 2
    } else if (f < 3) {
      nf = 3
    } else if (f < 5) {
      nf = 5
    } else {
      nf = 10
    }
  }
  val = nf * exp10 // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  // 20 is the uppper bound of toFixed.
  return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val
}
